import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import '../res/color_res.dart';

class VerificationButton extends StatefulWidget {
  const VerificationButton({
    super.key,
    required this.onPressed,
    this.countdownSeconds = 60,
    this.phoneNumber,
    this.width,
    this.height,
  });

  final Future<bool> Function() onPressed;
  final int countdownSeconds;
  final String? phoneNumber;
  final double? width;
  final double? height;

  @override
  createState() => _VerificationButtonState();
}

class _VerificationButtonState extends State<VerificationButton> {
  Timer? _timer;
  int _seconds = 0;
  bool _isCounting = false;
  DateTime? _endTime;

  void startCountdown() {
    _isCounting = true;
    _endTime = DateTime.now().add(Duration(seconds: widget.countdownSeconds));

    setState(() {
      _seconds = widget.countdownSeconds;
    });

    _timer = Timer.periodic(const Duration(milliseconds: 200), (timer) { // 提高刷新频率，体验更平滑
      final now = DateTime.now();
      final remaining = _endTime!.difference(now);

      // 关键改动在这里！
      final newSeconds = (remaining.inMilliseconds / 1000).ceil();

      // 只有在秒数真的改变时才调用setState，避免不必要的UI刷新
      if (newSeconds != _seconds) {
        setState(() {
          _seconds = newSeconds;
        });
      }

      if (remaining.isNegative) {
        setState(() {
          _seconds = 0;
          _isCounting = false;
          _timer?.cancel();
        });
      }
    });
  }

  @override
  void dispose() {
    _timer?.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final bool isPhoneValid =
        RegExp(r'^\d{11}$').hasMatch(widget.phoneNumber ?? '');

    return TextButton(
      onPressed: _isCounting || !isPhoneValid
          ? null
          : () async {
              try {
                final canStart = await widget.onPressed();
                if (canStart) {
                  startCountdown();
                }
              } catch (e) {

              }
            },
      style: TextButton.styleFrom(
        // minimumSize: Size(widget.width ?? 100.w, widget.height ?? 45.w),
        minimumSize: Size(90.w, 36.w),
        padding: EdgeInsets.symmetric(horizontal: 15.w, vertical: 8.w),
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(5.w),
        ),
        side: BorderSide(
          color: _isCounting || !isPhoneValid
              ? const Color(loginPageVerificationBtnUnable).withOpacity(0.5)
              : const Color(loginPageVerificationBtnActive),
        ),
      ),
      child: Text(
        _isCounting ? '${_seconds}s' : '获取验证码',
        style: TextStyle(
          fontSize: 12.sp,
          color: _isCounting || !isPhoneValid
              ? const Color(loginPageVerificationBtnUnable).withOpacity(0.5)
              : const Color(loginPageVerificationBtnActive),
        ),
      ),
    );
  }
}
